<template>
  <div class="main">
    <div class="topTitle">假期新增</div>
    <div class="form_content">
      <NScrollbar>
        <NSpin :show="spinShow">
          <div class="content">
            <NSpace>
              <NForm ref="formRef" :model="formValue" :rules="rules" label-placement="left" :label-width="130"
                label-align="right" require-mark-placement="left" style="width: 480rem">
                <NFormItem label="年份:" path="yearTime">
                  <NDatePicker input-readonly type="year" class="commonWidth" v-model:value="yearVal"
                    @update-formatted-value="handleYear" clearable />
                </NFormItem>
                <NFormItem label="天数：" path="addDay">
                  <NInput v-model:value="formValue.addDay" placeholder="输入天数" class="commonWidth"
                    :allow-input="onlyOneFloat" />
                </NFormItem>
                <NFormItem label="最后有效时间:" path="endTime">
                  <NDatePicker input-readonly type="date" class="commonWidth" v-model:value="dateVal"
                    @update-formatted-value="handleDate" clearable />
                </NFormItem>

                <NSpace style="display: flex; flex-direction: column">
                  <NFormItem label="应用人员范围:" path="scopeOrPeopleList">
                    <div style="width: 100%">
                      <NButton style="width: 115rem; margin-bottom: 10rem" type="primary" ghost @click="openScope">
                        选择应用人员
                      </NButton>
                      <div style="width: 100%">
                        <div class="scope">
                          <div class="userBox" v-for="(item, index) in formValue.scopeOrPeopleList" :key="index">
                            <div>{{ item.typeName }}</div>
                            <NIcon @click="handleScope(item.identifyingId)" style="cursor: pointer">
                              <CloseFilled />
                            </NIcon>
                          </div>
                        </div>
                      </div>
                    </div>
                  </NFormItem>
                </NSpace>
              </NForm>
            </NSpace>
          </div>
        </NSpin>
      </NScrollbar>
    </div>
  </div>
  <FixedAction>
    <NSpace justify="center">
      <NButton ghost @click="goBack">
        返回
      </NButton>
      <NButton type="primary" @click="confirm">
        提交
      </NButton>
    </NSpace>
  </FixedAction>
  <NModal :auto-focus="false" v-model:show="modalVisible" @close="modalVisible = false">
    <VScope @close="modalVisible = false" @scopeSubmit="getScopeList" :defaultList="scopeList" />
  </NModal>

  <NModal :auto-focus="false" v-model:show="modalVisibleA">
    <VDialogContent @close="modalVisibleA = false" @submit="againConfirm" title="保存提示">
      <div style="width: 300rem; height: 100rem; text-align: center; line-height: 100rem">
        您确定要保存吗?
      </div>
    </VDialogContent>
  </NModal>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import {
  NSpace,
  NForm,
  NInput,
  NFormItem,
  NButton,
  NModal,
  NScrollbar,
  NDatePicker,
  useMessage,
  NIcon,
  NSpin,
  type FormRules
} from 'naive-ui'
import type { FormInst } from 'naive-ui'
import { useTagStore } from '@/stores/layout'
import FixedAction from '@/components/FixedAction.vue'
import router from '@/router'
import { sendRequest } from '@/utils/api'
import type { HttpResponse } from '@/utils/http'
import VScope from '@/views/OA/Common/Scope.vue'
import { CloseFilled } from '@vicons/material'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'

const tags = useTagStore().tags

const spinShow = ref(false)

const message = useMessage()

const formRef = ref<FormInst | null>(null)

type formType = {
  yearTime: any
  addDay: any
  endTime: any
  scopeOrPeopleList: any
}
const formValue = reactive<formType>({
  yearTime: null,
  addDay: null,
  endTime: null,
  scopeOrPeopleList: null
})
const rules: FormRules = {
  addDay: {
    required: true,
    trigger: ['input', 'blur'],
    validator: (_: any, value: any) => {
      if (!value) return new Error('请输入天数')
      if (value.length > 100) return new Error('天数字数不得超过100')
      return true
    }
  },
  yearTime: {
    required: true,
    message: '请选择年份',
    trigger: ['change']
  },
  endTime: {
    required: true,
    message: '请选择最后有效时间',
    trigger: ['change']
  },
  scopeOrPeopleList: {
    required: true,
    message: '请选择应用人员范围',
    type: 'array',
    trigger: ['change', 'input']
  },
}

//只能输入数字
const onlyOneFloat = (value: string) => {
  if (Number(value) > 100) {
    message.error('假期天数不可超过100天!')
  }
  var t = /^[0-9]+([.][0-9]{0,1})?$/
  return !value || t.test(value) && Number(value) <= 100
}


//日期选择器
const yearVal: any = ref()
const dateVal: any = ref()
function handleYear(e: string[]) {
  if (yearVal.value == null) {
    formValue.yearTime = null
  } else {
    formValue.yearTime = e
  }
}
function handleDate(e: string[]) {
  if (yearVal.value == null) {
    formValue.endTime = null
  } else {
    formValue.endTime = e
  }
}

// 返回
const goBack = () => {
  const index = tags.findIndex((item: any) => item.path === router.currentRoute.value.fullPath)
  tags.splice(index, 1)
  router.push({ path: '/OA/Office/holidaySetting' })
}

// 确定
const modalVisibleA = ref(false)
const confirm = () => {
  formRef.value?.validate(async (err: any) => {
    if (err) return
    if (formValue.scopeOrPeopleList) {
      modalVisibleA.value = true
    } else {
      message.warning('请选择应用人员范围！')
    }
  })
}

const againConfirm = async () => {
  spinShow.value = true
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'office',
    api: 'holidaySave',
    override: {
      data: {
        ...formValue
      }
    }
  })
  if (error) return message.error(error.message)
  message.success(res.msg)
  modalVisibleA.value = false
  spinShow.value = false
  goBack()
}

// 打开发布范围
const modalVisible = ref(false)
const scopeList = ref()
const openScope = () => {
  scopeList.value = formValue.scopeOrPeopleList
  modalVisible.value = true
}
// 发布范围选择
const getScopeList = (v: any) => {
  console.log(v)
  formValue.scopeOrPeopleList = v
  modalVisible.value = false
}
// 范围选择是删除
const handleScope = (id: any) => {
  const index = formValue.scopeOrPeopleList.findIndex((it: any) => it.identifyingId == id)
  formValue.scopeOrPeopleList.splice(index, 1)
}
</script>

<style scoped lang="scss">
@mixin CommonFont {
  font-size: 16rem;
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.85);
}

.commonWidth {
  width: 360rem;
}

.main {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  overflow: hidden;

  .topTitle {
    width: 100%;
    height: 64rem;
    border-bottom: 1px solid #fff;
    padding: 20rem;
    margin-bottom: 20rem;
    @include CommonFont;
  }

  .form_content {
    width: 100%;
    height: 100%;
    padding: 0 20rem 0rem;

    .content {
      display: flex;
      align-items: center;
      flex-direction: column;
      width: 100%;
      height: 100%;
      padding: 20rem 0 180rem;
      overflow-y: scroll;
      background-color: #ebeceb;

      .scope {
        display: flex;
        flex-wrap: wrap;
        width: 100%;
        height: auto;
        min-height: 130rem;
        background: #e1e1e1;
        padding: 15rem 20rem;

        .userBox {
          display: flex;
          justify-content: space-between;
          align-items: center;
          width: auto;
          min-width: 150rem;
          height: 40rem;
          background-color: #fff;
          border-radius: 4rem;
          padding: 0 10rem;
          margin-right: 20rem;
          margin-bottom: 10rem;
        }
      }
    }
  }
}

.content::-webkit-scrollbar {
  display: none;
}

.commonWidth {
  width: 360rem;
}
</style>
